import logging
import os
from datetime import datetime

from django.core.paginator import Paginator
from django.shortcuts import render
from matplotlib import pyplot as plt

from news.settings import STATIC_URL, STATICFILES_DIRS
from .models import News
from .service import wordcloudService


# Create your views here.

def index(request):
    news = News.objects.order_by('-id').order_by('-num').first()
    # 获取最大的ID值
    max_id = News.objects.all().order_by('-num')[0].num
    # 获取ID小于最大ID的第二条数据
    #second_record = News.objects.filter(num__lt=max_id).order_by('-num')[1]
    path = str("images/news/") + getDate() + str('.png')
    pic_url = str("app/static/") + path

    if os.path.exists(pic_url):
        logging.Logger("Picture exists")
    else:
        image_data = wordcloudService.do_image()
        # 生成图像的代码...
        fig, ax = plt.subplots()
        ax.imshow(image_data, cmap='gray')  # 将 image_data 替换为你的图像数据
        plt.axis('off')  # 关闭坐标轴
        plt.savefig(pic_url, bbox_inches='tight', pad_inches=0)  # 将图像保存为临时文件
        plt.close()


    newsList = News.objects.all().filter(num__lt=max_id).order_by('-id').order_by('-num')

    # 创建一个 Paginator 实例，每页显示 10 条数据
    paginator = Paginator(newsList[2:], 10, 2)
    # 获取当前页码，默认为第 1 页
    page_number = 1
    newsList = paginator.get_page(page_number)

    return render(request, 'index.html', {'news': news, 'newsList': newsList, 'pic_url': path})


def about(request):
    return render(request, 'about.html')


def contact(request):
    return render(request, 'contact.html')


def codes(request):
    return render(request, 'codes.html')


def fashion(request):
    return render(request, 'fashion.html')


def music(request):
    return render(request, 'music.html')


def features(request):
    return render(request, 'features.html')


def travel(request):
    return render(request, 'travel.html')


def singlepage(request):
    return render(request, 'singlepage.html')


def weather(request):
    return render(request, 'weather.html')


def getDate():
    date_object = datetime.now()
    date_string = date_object.strftime("%Y%m%d")
    return date_string
